#!/usr/bin/perl -w
##This script is used to generate Cluster3 compatible matrix for heatmap plotting

## author: Yaping Liu  lyping1986@gmail.com 
## time: 2013-2-26

#Usage:  perl generate_heatmap_matrix.pl [OPTION] align.txt 
use strict;
use Getopt::Long;

my $smooth = "";
my $bin_size = 20;
my $data_matrix_scale= 1200;

GetOptions( "smooth" => \$smooth,
			"data_matrix_scale=i" => \$data_matrix_scale,
			"bin_size=i" => \$bin_size,
);

my $file=$ARGV[0];
	open(FH,"<$file") or die "can not open file:$!";
	my $location = $file;
	$location =~ s/\.txt//;
	$location .= ".heatmap.matrixForCluster3.txt";
	open(OUT,">$location") or die "can not open file:$!";
	print OUT "Genes\t";
	for(my $i=0-$data_matrix_scale;$i<=$data_matrix_scale; $i++){
		if($i==$data_matrix_scale){
			print OUT "$i";
		}
		else{
			print OUT "$i\t";
		}
		
	}
	print OUT "\n";
	while(<FH>){
		chomp;
		my $line = $_;
		my @splitin = split "\t",$line;
		#print "$#splitin\t$data_matrix_scale\n";
		if($#splitin == $data_matrix_scale * 2 + 4){
			my $header = join ":",$splitin[0],$splitin[1],$splitin[2],$splitin[3];
			print OUT "$header\t";
			for(my $i=4;$i<$data_matrix_scale * 2+4; $i++){
				if($smooth ne ""){
					my $sum=0;
					my $num=0;
					for(my $j=$i-int($bin_size/2);$j<=$i+int($bin_size/2); $j++){
						if($j>=4 and $j < ($data_matrix_scale * 2+4)){
							if($splitin[$j] ne "NaN"){
								$sum += $splitin[$j];
								$num++;
							}
						
						}
					
					}
					if($num == 0){
						print OUT "NA\t";
					}
					else{
						my $methy = $sum/$num;
						print OUT "$methy\t";
					}
					
				}
				else{
					if($splitin[$i] eq "NaN"){
						print OUT "NA\t";
					}
					else{
						print OUT "$splitin[$i]\t";
					}
					
				}
				
			}
			print OUT "\n";

		}
		
	}
	close(FH);
	close(OUT);